/*
 * JobRunnerServlet.java
 *
 */

package com.scalar.chiptrack.jobs;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scalar.chiptrack.jobs.JobRunner;
import com.scalar.chiptrack.jobs.dao.JobDAO;



public class JobRunnerServlet extends HttpServlet {
    
    private JobRunner m_jobRunner = null;

    
    /** Initializes the servlet.
     */
    public void init (ServletConfig config) throws ServletException {
        super.init(config);

        //Updating the On Demand Adaptor Stauts to 1. i.e updating Status to Stopped.
        try {
            JobDAO.updateOnDemandAdaptorStatus( Boolean.FALSE );
        } catch( Exception e ) {
            System.out.println("Unable to Update Run Adaptor Stauts.");
        }

        //Getting Previous Scheduler Status from DB.
        boolean schedulerstatus = JobDAO.getSchedulerStatus();

        // If It's in Running Status(means 0 Value in DB), Starting The Scheduler.
        if ( schedulerstatus == true )
        {
            System.out.print ("Starting up ChipTrac Job Scheduler...");
            m_jobRunner = JobRunner.getInstance();
            m_jobRunner.start();
            System.out.println ("done");
        }
    }
    
    /** Destroys the servlet.
     */
    public void destroy() {
        if (m_jobRunner != null) {
            System.out.print ("Stopping ChipTrac Job Scheduler...");
            m_jobRunner.stop();
            System.out.println ("done");
        }
    }
    

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void service (HttpServletRequest request, HttpServletResponse response)
                                                throws ServletException, java.io.IOException {

        /*response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        
         // output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet</title>");
        out.println("</head>");
        out.println("<body>");
         
        out.println("</body>");
        out.println("</html>");
         
        out.close();*/
    }
    
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Starts JobRunner when server starts up";
    }
    
}
